import json

import requests

if __name__ == "__main__":
    your_api_key = ''  # 此处添加你申请的api_key
    video_id = ''  # 这里添加要获取视频的video_id
    url = 'https://youtube.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies'
    header = {
        "user-agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36 OPR/84.0.4316.31',
        'Content-Type': 'application/json;charset=UTF-8',
    }
    params = {
        'maxResults': 5000,
        'textFormat': 'plainText',
        'videoId': video_id,
        'key': your_api_key
    }
    s = requests.get(url=url, headers=header, params=params)
    print(s.text)
    count = 0
    with open('data.txt', 'a', encoding='utf-8') as f:
        for i in s.json()['items']:
            print(count, i)
            f.write(json.dumps(i))
            f.write('\n')
            count += 1
    print('-' * 60)
    next_token = s.json()['nextPageToken']
    try:
        while next_token != None:
            params = {
                'maxResults': 5000,
                'textFormat': 'plainText',
                'videoId': video_id,
                'pageToken': next_token,
                'key': your_api_key
            }
            s = requests.get(url=url, headers=header, params=params)
            # print(s.text)
            with open('data.txt', 'a', encoding='utf-8') as f:
                for i in s.json()['items']:
                    print(count, i)
                    f.write(json.dumps(i))
                    f.write('\n')
                    count += 1
            next_token = s.json()['nextPageToken']
    except:
        print(s.text)
